import { handleRouter } from './handle-router'

let prevRouter = '' // 上一个路由
let nextRouter = window.location.pathname // 下一个路由

export const getPrevRouter = () => prevRouter
export const getNextRouter = () => nextRouter

export const rewriteRouter = () => {
  window.addEventListener('popstate', () => {
    prevRouter = nextRouter
    nextRouter = window.location.pathname
    handleRouter()
  })

  const rawPushState = window.history.pushState
  window.history.pushState = (...args) => {
    // 导航前
    prevRouter = window.location.pathname
    rawPushState.apply(window.history, args)

    // 导航后
    nextRouter = window.location.pathname
    handleRouter()
  }

  const rawReplaceState = window.history.replaceState
  window.history.pushState = (...args) => {
    // 导航前
    prevRouter = window.location.pathname
    rawReplaceState.apply(window.history, args)

    // 导航后
    nextRouter = window.location.pathname
    handleRouter()
  }
}
